<?php

/**
 * @author Eureka
 */
class Items extends CActiveRecord
{

    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    public function tableName()
    {
        return 'items';
    }

    public function listItem()
    {
        $criteria = new CDbCriteria;

        return new CActiveDataProvider(get_class($this), array(
                    'criteria' => $criteria,
                    'sort' => array(
                        'defaultOrder' => 'title ASC',
                    ),
                    'pagination' => array(
                        'pageSize' => 5
                    ),
                ));
    }

    public function findAllByTags($tag_id)
    {
        $command = Yii::app()->db->createCommand();
        $result = $command->select('*')
                ->from('items i')
                ->leftJoin('item_tags it', 'it.item_id = i.id')
                ->leftJoin('tags t', 't.id = it.tag_id')
                ->where('t.id=:tag_id', array(':tag_id' => $tag_id))
                ->queryAll();
        return $result;
    }

    public function relations()
    {
        return array(
            'shops' => array(
                self::BELONGS_TO, 'Shops', 'shop_id'
            ),
            'item_tags' => array(
                self::MANY_MANY, 'ItemTags', 'item_tags(item_id, tag_id)', 'index' => 'tag_id'
            ),
        );
    }

}
